#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
通知服务模块
负责将投资策略报告推送到微信或短信
"""

import os
import json
import yaml
import logging
import requests
from datetime import datetime
from pathlib import Path

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

class NotificationService:
    """通知服务类，负责将策略报告推送到不同的通知渠道"""
    
    def __init__(self, config_path='config/config.yaml'):
        """
        初始化通知服务
        
        Args:
            config_path: 配置文件路径
        """
        self.config_path = config_path
        self.config = self._load_config()
        self.notification_config = self.config.get('notification', {})
        logger.info("通知服务初始化完成")
    
    def _load_config(self):
        """
        加载配置文件
        
        Returns:
            dict: 配置信息
        """
        try:
            with open(self.config_path, 'r', encoding='utf-8') as f:
                config = yaml.safe_load(f)
            logger.info(f"成功加载配置文件: {self.config_path}")
            return config
        except Exception as e:
            logger.error(f"加载配置文件失败: {e}")
            return {}
    
    def send_wechat_notification(self, title, content, report_path=None):
        """
        发送微信通知
        
        Args:
            title: 通知标题
            content: 通知内容
            report_path: 报告文件路径，可选
            
        Returns:
            bool: 是否发送成功
        """
        try:
            wechat_config = self.notification_config.get('wechat', {})
            if not wechat_config or not wechat_config.get('enabled', False):
                logger.warning("微信通知未启用")
                return False
            
            # 获取微信公众号配置
            app_id = wechat_config.get('app_id')
            app_secret = wechat_config.get('app_secret')
            template_id = wechat_config.get('template_id')
            user_ids = wechat_config.get('user_ids', [])
            
            if not (app_id and app_secret and template_id and user_ids):
                logger.warning("微信通知配置不完整")
                return False
            
            # 构建通知内容
            notification_data = {
                "title": {"value": title, "color": "#173177"},
                "strategy": {"value": content[:100] + "...", "color": "#173177"},
                "time": {"value": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "color": "#173177"}
            }
            
            # 获取访问令牌
            token_url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={app_id}&secret={app_secret}"
            token_response = requests.get(token_url)
            token_data = token_response.json()
            
            if 'access_token' not in token_data:
                logger.error(f"获取微信访问令牌失败: {token_data}")
                return False
            
            access_token = token_data['access_token']
            
            # 发送模板消息
            success_count = 0
            for user_id in user_ids:
                template_msg = {
                    "touser": user_id,
                    "template_id": template_id,
                    "url": wechat_config.get('web_url', ''),
                    "data": notification_data
                }
                
                send_url = f"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}"
                response = requests.post(send_url, json=template_msg)
                result = response.json()
                
                if result.get('errcode') == 0:
                    success_count += 1
                else:
                    logger.error(f"发送微信通知失败: {result}")
            
            logger.info(f"已成功发送微信通知给 {success_count}/{len(user_ids)} 位用户")
            return success_count > 0
            
        except Exception as e:
            logger.error(f"发送微信通知异常: {e}")
            return False
    
    def send_sms_notification(self, title, content):
        """
        发送短信通知
        
        Args:
            title: 通知标题
            content: 通知内容
            
        Returns:
            bool: 是否发送成功
        """
        try:
            sms_config = self.notification_config.get('sms', {})
            if not sms_config or not sms_config.get('enabled', False):
                logger.warning("短信通知未启用")
                return False
            
            # 获取短信服务配置
            api_key = sms_config.get('api_key')
            api_secret = sms_config.get('api_secret')
            sign_name = sms_config.get('sign_name')
            template_code = sms_config.get('template_code')
            phone_numbers = sms_config.get('phone_numbers', [])
            
            if not (api_key and api_secret and sign_name and template_code and phone_numbers):
                logger.warning("短信通知配置不完整")
                return False
            
            # 构建短信内容
            sms_text = f"{title}: {content[:50]}..."
            
            # 这里应该根据实际使用的短信服务提供商调整API调用方式
            # 以下是一个示例，需要根据实际情况修改
            api_url = sms_config.get('api_url', 'https://api.sms-service.com/send')
            
            success_count = 0
            for phone in phone_numbers:
                params = {
                    'apikey': api_key,
                    'secret': api_secret,
                    'phone': phone,
                    'template': template_code,
                    'sign': sign_name,
                    'params': json.dumps({'content': sms_text})
                }
                
                response = requests.post(api_url, data=params)
                result = response.json()
                
                if result.get('code') == 0:
                    success_count += 1
                else:
                    logger.error(f"发送短信通知失败: {result}")
            
            logger.info(f"已成功发送短信通知给 {success_count}/{len(phone_numbers)} 个手机号")
            return success_count > 0
            
        except Exception as e:
            logger.error(f"发送短信通知异常: {e}")
            return False
    
    def send_notification(self, title, content, report_path=None, channels=None):
        """
        发送通知到指定的渠道
        
        Args:
            title: 通知标题
            content: 通知内容
            report_path: 报告文件路径，可选
            channels: 通知渠道列表，可选，默认使用配置文件中启用的所有渠道
            
        Returns:
            dict: 各渠道的发送结果
        """
        results = {}
        
        if channels is None:
            # 使用配置中启用的所有渠道
            channels = []
            if self.notification_config.get('wechat', {}).get('enabled', False):
                channels.append('wechat')
            if self.notification_config.get('sms', {}).get('enabled', False):
                channels.append('sms')
        
        # 发送到各个渠道
        for channel in channels:
            if channel == 'wechat':
                results['wechat'] = self.send_wechat_notification(title, content, report_path)
            elif channel == 'sms':
                results['sms'] = self.send_sms_notification(title, content)
            else:
                logger.warning(f"未知的通知渠道: {channel}")
                results[channel] = False
        
        return results 